/*
* MouseCaptureHelper
*
* Written by Greg Zubankov (greg@ss.penza.net).
* Copyright (c) 2005 Greg Zubankov.
*/

#ifndef VS_MOUSER_CAPTURE_HELPER_INC
#define VS_MOUSER_CAPTURE_HELPER_INC


namespace vs
{

  // CaptureHelper
  template <class T>
  class MouseCaptureHelper
  {
  public:
    typedef MouseCaptureHelper<T> MouseCaptureHelperT;

    MouseCaptureHelper()
      : isMouseCaptured_(false)
    {}

  // CRTP interface
  public:
    void OnLoseCapture()
    {
      ATLASSERT(!"MouseCaptureHelper::OnLoseCapture must be implemented in derived class!");
    }

  public:
    void CaptureMouse()
    {
      if(!IsMouseCaptured())
      {
        static_cast<T&>(*this).SetCapture();
        isMouseCaptured_ = true;
      }
    }

    void ReleaseMouse()
    {
      if(IsMouseCaptured())
      {
        ReleaseCapture();
        isMouseCaptured_ = false;
      }
    }

    bool IsMouseCaptured()
    {
      return isMouseCaptured_;
    }

  protected:
    BEGIN_MSG_MAP_EX(MouseCaptureHelperT)
      MSG_WM_CAPTURECHANGED(OnCaptureChanged)
    END_MSG_MAP()

  private:
    void OnCaptureChanged(CWindow)
    {
      isMouseCaptured_ = false;
      static_cast<T&>(*this).OnLoseCapture();
      SetMsgHandled(false);
    }

  private:
    bool isMouseCaptured_;
  };

} // namespace vs


#endif  // VS_MOUSER_CAPTURE_HELPER_INC
